package com.maximus.server;

import com.maximus.server.nio.mainsubreactor.MainReactor;
import com.maximus.server.nio.multithreadingReactor.MultiThreadReactor;
import com.maximus.server.nio.normal.NioServer;
import com.maximus.server.nio.singlethreadreactor.SingleThreadReactor;
import com.maximus.server.socket.SocketRunner;
import com.maximus.server.socket.SocketServerPoolHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class RedisServer {
    private static final Logger logger = LogManager.getLogger(RedisServer.class);
    private final int port;

    public RedisServer(int port) {
        this.port = port;
    }

    //BIO模式
    public void bioStart() {
        logger.info("bio模式启动...");
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            SocketServerPoolHandler poolHandler = new SocketServerPoolHandler(3, 10);
            while (true) {
                // 等待连接
                Socket socket = serverSocket.accept();

                //连接后开一个线程处理，一个连接一个线程
                SocketRunner socketRunner = new SocketRunner(socket);
                poolHandler.execute(socketRunner);

            }
        } catch (IOException e) {
            logger.error(e);
        }
    }

    public void nio() {
        logger.info("普通nio模式启动...");
        try {
            NioServer nioServer = new NioServer(port);
            nioServer.listen();
        } catch (IOException e) {
            logger.error(e);
        }
    }

    //NIO 单线程reactor模式
    public void nioSingleThreadReactorStart() {
        logger.info("单线程reactor模式启动...");
        try {
            //单线程reactor
            SingleThreadReactor singleThreadReactor = new SingleThreadReactor(port);
            singleThreadReactor.run();
        } catch (IOException e) {
            logger.error(e);
        }
    }

    //NIO 多线程reactor模式
    public void nioMultiThreadReactorStart() {
        logger.info("多线程reactor模式启动...");
        try {
            MultiThreadReactor multiThreadReactor = new MultiThreadReactor(port);
            multiThreadReactor.run();
        } catch (IOException e) {
            logger.error(e);
        }
    }

    public void MainSubReactorStart() {
        logger.info("主从reactor模式启动...");
        MainReactor mainReactor = new MainReactor(port);
        mainReactor.run();
    }

}
